<template>
  <div>
    <!-- 角色列表 -->
    <el-select v-model="selectedRole" placeholder="请选择角色">
      <el-option
          v-for="role in roleList"
          :key="role.id"
          :label="role.name"
          :value="role.id"
      />
    </el-select>

    <!-- 用户表格 -->
    <el-table :data="users" style="width: 100%">
      <el-table-column prop="userName" label="用户名" width="180"></el-table-column>
      <el-table-column prop="role" label="角色名" width="180"></el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="editUser(row)">编辑</el-button>
          <el-button type="danger" size="small" @click="deleteUser(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增按钮 -->
    <el-button type="success" @click="addUserDialog">新增用户</el-button>

    <!-- 新增/编辑用户的对话框 -->
    <el-dialog v-model="dialogVisible" title="用户信息">
      <el-form :model="form">
        <el-form-item label="用户名" :label-width="formLabelWidth">
          <el-input v-model="form.userName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth">
          <el-input v-model="form.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色" :label-width="formLabelWidth">
          <el-select v-model="form.role" placeholder="请选择角色">
            <el-option
                v-for="role in roleList"
                :key="role.id"
                :label="role.name"
                :value="role.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveUser">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';

const API_URL = 'http://60.205.189.235:90/api/v1/role'

export default {
  data() {
    return {
      users: [], // 用户列表
      roleList: [], // 角色列表
      dialogVisible: false, // 对话框是否可见
      form: {
        id: null,
        userName: '',
        password: '',
        roleId: null,
        role: ''
      },
      formLabelWidth: '120px',
      selectedRole: null
    };
  },
  created() {
    this.fetchRoles();
    this.fetchUsers();
  },
  methods: {
    async fetchRoles() {
      try {
        const response = await axios.post(API_URL + '/selectAllRole');
        this.roleList = response.data;
        console.log("角色列表：", JSON.stringify(this.roleList, null, 2));
      } catch (error) {
        console.error("Error fetching roles:", error);
      }
    },
    async fetchUsers() {
      try {
        const response = await axios.post(API_URL + '/getAllUsers');
        this.users = response.data.map(user => ({
          ...user,
          roleName: this.roleList.find(role => role.id === user.roleId)?.name || ''
        }));
        console.log("用户列表：", JSON.stringify(this.users, null, 2));
      } catch (error) {
        console.error("Error fetching users:", error);
      }
    },
    editUser(row) {
      this.form = { ...row, roleName: this.roleList.find(role => role.id === row.roleId)?.name || '' };
      this.dialogVisible = true;
    },
    deleteUser(row) {
      this.users = this.users.filter(user => user.id !== row.id);
      this.saveUserChanges();
    },
    addUserDialog() {
      this.form = {
        id: null,
        userName: '',
        password: '',
        roleId: null,
        role: ''
      };
      this.dialogVisible = true;
    },
    saveUser() {
      if (this.form.id) {
        this.updateUser();
      } else {
        this.addUser();
      }
      this.dialogVisible = false;
    },
    addUser() {
      this.users.push({
        ...this.form,
        roleName: this.roleList.find(role => role.id === this.form.roleId)?.name || ''
      });
      this.saveUserChanges();
    },
    updateUser() {
      const index = this.users.findIndex(user => user.id === this.form.id);
      if (index !== -1) {
        this.users[index] = {
          ...this.form,
          roleName: this.roleList.find(role => role.id === this.form.roleId)?.name || ''
        };
        this.saveUserChanges();
      }
    },
    async saveUserChanges() {
      try {
        const response = await axios.post(API_URL + '/saveUser', this.form);
        console.log("保存用户成功：", response.data);
      } catch (error) {
        console.error("Error saving user:", error);
      }
    }
  }
};
</script>

<style scoped>
.el-table {
  margin-top: 20px;
}
</style>
